# -*- coding:utf-8 -*-

import csv
import os

import pandas as pd
import requests

requests.packages.urllib3.disable_warnings()  # 忽略HTTPS安全警告

"""
自定义请求工具
"""


class HttpUtils():
    """
    自定义请求工具
    """
    @staticmethod
    def do_request(method, url, headers, data, max_retry=3, retry=1):
        """
        Http请求

        :param method: 请求类型 GET、POST
        :param url: 请求地址
        :param headers: 请求头
        :param data: 请求参数
        :param max_retry: 重试最大次数 默认3次
        :param retry: 重试次数。默认值1
        :return: 返回http
        """
        # cookies = self.get_cookie_dict("JSESSIONID=D79B2E69AADDABD4A2A0B5352C4A1987")
        # allow_redirects=False 不允许跳转 默认True
        res = None
        try:
            match method:
                case "POST":
                    if url.find("https") == 0:
                        res = requests.post(url, headers=headers, data=data, verify=False)
                    else:
                        res = requests.post(url, headers=headers, data=data)
                case "GET":
                    if url.find("https") == 0:
                        res = requests.get(url, headers=headers, params=data, verify=False)
                    else:
                        res = requests.get(url, headers=headers, params=data)
                case _:
                    res = None
        except Exception as ex:
            print(f"-------------【错误】,重试第【{retry}】次-------------")
            print(ex)
            if retry <= max_retry:
                retry += 1
                return HttpUtils.do_request(method, url, headers, data, max_retry, retry)
        else:
            if res.status_code != 200:
                if retry <= max_retry:
                    print(f"-------------状态码:{res.status_code},重试第【{retry}】次-------------")
                    retry += 1
                    return HttpUtils.do_request(method, url, headers, data, max_retry, retry)
        return res

    @staticmethod
    def get_cookies_str(cookies_dict: dict):
        """
        将cookies_dict拼接字符串

        :param cookies_dict:COOKIES
        :return:返回字符串
        """
        cookies_str = ""
        for key, value in cookies_dict.items():
            cookies_str += key + "=" + value + ";"

        return cookies_str

    @staticmethod
    def get_cookie_dict(cookies_str: str):
        """
        将字符串转换dict格式

        :return:
        """
        itemDict = {}
        items = cookies_str.split(';')
        for item in items:
            arr = item.split('=')
            key = arr[0].replace(' ', '')
            value = arr[1]
            itemDict[key] = value
        return itemDict

    @staticmethod
    def dict_to_csv(filename: str, item: dict):
        """
        dict保存excel

        :param filename: 文件名称
        :param item: 保存的数据
        :return: 无返回
        """
        savefileName = "./" + filename + ".csv"  # "./result.csv"
        headList = []  # 键list
        saveList = []  # 值list

        for k, v in item.items():
            headList.append(k)
            saveList.append(v)
        # 如果文件不存在，创建头
        if not os.path.exists(savefileName):
            with open(savefileName, "a", encoding="utf-8-sig", newline="") as csvfile:
                writer = csv.writer(csvfile)
                writer.writerow(headList)
        # 保存item中的数据
        with open(savefileName, "a", encoding="utf-8-sig", newline="") as csvfile:
            writer = csv.writer(csvfile)
            writer.writerow(saveList)

        print(str(item))

    @staticmethod
    def check_data(source_path, target_path):
        """
        提取待搜索的关键词。根据source_path路径的文件与target_path路径文件比对待搜索的关键词。

        :param source_path:原关键词文件路径
        :param target_path:已经查询好的文件路径
        :return: search_list：全部关键词列表。line_num：该查询关键词所在的行号。target_path：保存文件路径
        """
        source_list = []
        source_list1 = []
        target_list = []
        target_value_list = []
        search_list = []
        search_list1 = []
        source_list_count = 0
        target_list_count = 0
        search_list_count = 0

        line_num = 0
        # source_path文件
        df_s = pd.read_excel(source_path, sheet_name=0)
        for index, row in df_s.iterrows():
            # source_list.append(str(row[0]).strip())
            # # 浓度
            # source_list1.append(str(row[1]).replace(" ", "").strip())
            if len(str(row[0])) > 4 and len(str(row[1])) > 4:
                source_list.append(str(row[0]).strip())
                # 浓度
                source_list1.append(str(row[1]).replace(" ", "").strip())

        source_list_count = len(source_list)

        # 如果有target_path文件
        if os.path.exists(target_path):
            # target_path文件
            df_t = pd.read_csv(target_path, header=None)
            for index, row in df_t.iterrows():
                target_list.append(str(row[0]).strip())
                target_value_list.append(str(row[1]).strip())

            target_list_count = len(target_list)

        # 对比未搜索的关键词，并将结果保存到search_list
        for i in range(0, source_list_count):
            if source_list[i] in target_list:
                pass
            else:
                search_list.append(source_list[i].strip())

        search_list_count = len(search_list)

        return search_list, line_num, target_path

    @staticmethod
    def down_file(file_url, headers, filename):
        """
        下载文件、图片

        :param file_url: 图片链接地址
        :param headers:请求头
        :param filename: 图片名称+扩展名
        :return:
        """
        print(f"============下载文件中===============")
        fileStream = HttpUtils.do_request("GET", file_url, headers, "").content
        savefileName = "./" + filename
        with open(savefileName, "wb") as f:
            f.write(fileStream)
        print(f"============下载【{filename}】完成===============")